<?php

namespace app\common\services;

use api\upload\exception\UploadException;
use api\upload\Upload;
use app\common\repositories\system\upload\SystemUploadConfigRepository;

class UploadService
{
    /**
     * 初始化
     *
     * @param int $itemsId 企业ID
     * @param string $dir 上传目录
     * @param string $driver 上传驱动
     * @return Upload
     * @throws UploadException
     */
    public static function init(int $itemsId, string $dir = '', string $driver = ''): Upload
    {
        /** @var SystemUploadConfigRepository $systemUploadConfigRepository */
        $systemUploadConfigRepository = app()->make(SystemUploadConfigRepository::class);

        $config = $systemUploadConfigRepository->getConfig($itemsId);
        $config = self::getConfig($config);
        if (!$config || !is_array($config)) {
            throw new UploadException('未配置上传参数');
        }

        /** @var Upload $upload */
        $upload = app()->make(Upload::class, [$config, $dir, $driver ?: ($config['upload_type'] ?? 'local')]);
        $upload->setConfig($config);

        $upload->setDriver($driver ?: ($config['upload_type'] ?? 'local'));

        return $upload;
    }

    private static function getConfig($config)
    {
        if (!$config) {
            $data = [
                'upload_type' => 'local',
                'upload_allow_ext' => 'gif,ico,icon,jpg,jpeg,png'
            ];
        } else {
            $data = [
                'upload_type' => $config['type_platform'],
                'upload_allow_ext' => $config['file_type'],
            ];
            $data[$config['type_platform']] = [
                'bucket' => $config['bucket_name'],
                'endpoint' => $config['regional_node'],
                'access_key_id' => $config['access_key'],
                'access_key_secret' => $config['key_secret'],
                'domain' => $config['domain_url'],
            ];
        }

        return $data;
    }
}